import logging
import os
import rclpy
import rclpy
from rclpy.node import Node
from std_msgs.msg import Bool
import threading
from . import snowboydecoder

PACKAGE_NAME = 'robot_voice'
PACKAGE_DIR = os.path.join(os.path.dirname(
    os.path.abspath(__file__)), "../../../../share", PACKAGE_NAME)
MODEL = os.path.join(PACKAGE_DIR, "models", "white.pmdl")
TONE = os.path.join(PACKAGE_DIR, "assets", "message.wav")

interrupted = False
logger = logging.getLogger("snowboy")
logger.setLevel(logging.DEBUG)

def interrupt_callback():
    global interrupted
    return interrupted


class WakeUp(Node):
    def __init__(self, name):
        super().__init__(name)
        self.get_logger().info("启动节点: %s" % name)
        self.wake_up_publisher = self.create_publisher(
            Bool, "wake_up", 10)

        detector_thread = threading.Thread(target=self.detector_thread)
        detector_thread.start()

    def detector_thread(self):
        detector = snowboydecoder.HotwordDetector(MODEL, sensitivity=0.5)
        self.get_logger().info("正在等待唤醒...")
        detector.start(detected_callback=self.detected_callback,
                       interrupt_check=interrupt_callback,
                       sleep_time=3)
        detector.terminate()

    def detected_callback(self):
        self.get_logger().info("收到")
        self.wake_up_publisher.publish(Bool(data=True))
        snowboydecoder.play_audio_file(TONE)


def main(args=None):
    rclpy.init(args=args)
    node = WakeUp("wake_up")
    rclpy.spin(node)
    rclpy.shutdown()
    interrupted = True
